<template>

  <div>
    <!-- Breadcrumb 面包屑 导航区-->
    <!-- <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">后台角色管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>后台角色列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <!-- Card 卡片 卡片视图区-->
    <el-card class="box-card">
      <!-- 添加按钮区-->
      <div><el-button
        type="primary"
        @click="addDialogVisible = true"
      >添加角色</el-button></div>
      <!-- 表格区-->
      <el-table :data="dataList" border stripe>
        <el-table-column type="index" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="remarks" label="角色说明" />

        <el-table-column label="操作">
          <!-- 操作模板-->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="DelbyID(scope.row.id)"
            >删除</el-button>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域-->
      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 修改用户信息的对话框-->
    <el-dialog
      title="修改后台角色信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="EditDialogClosed"
    >
      <div>
        <el-form ref="editform" :model="roleInfo" :rules="editrules">
          <el-form-item label="角色说明：" prop="remarks">
            <el-input v-model="roleInfo.remarks" />
          </el-form-item>
          <el-form-item label="角色名称：" prop="roleName">
            <el-input v-model="roleInfo.roleName" />
          </el-form-item>
          <!--  树形控件区-->
          <!-- node-key每个树节点用来作为唯一标识的属性，整棵树应该是唯一的-->
          <el-tree
            ref="treeRef"
            :data="PermissiondataList"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :default-checked-keys="defaultCheckedKkeys"
            :props="treeProps"
            @check="setChecked"
          />
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogClosed">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户信息的对话框-->
    <el-dialog
      title="添加后台角色信息"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <div>
        <el-form ref="addform" :model="roleInfo" :rules="editrules">

          <el-form-item label="角色说明：" prop="remarks">
            <el-input v-model="roleInfo.remarks" />
          </el-form-item>
          <el-form-item label="角色名称：" prop="roleName">
            <el-input v-model="roleInfo.roleName" />
          </el-form-item>
          <!--  树形控件区-->
          <!-- node-key每个树节点用来作为唯一标识的属性，整棵树应该是唯一的-->
          <el-tree
            ref="treeRef"
            :data="PermissiondataList"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :default-checked-keys="defaultCheckedKkeys"
            :props="treeProps"
            @check="setChecked"
          />
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

export default {

  data() {
    return {
      treeProps: {
        // 树形控件的属性绑定
        children: 'children',
        label: 'remarks' // 用权限的remarks字段做label
      },
      defaultCheckedKkeys: [], // 默认选中的节点数组
      PermissiondataList: null, // 权限列表
      // 获取用户列表参数
      queryInfo: {
      // query: '',
        pagenum: 1, // 当前页码数
        pagesize: 5 // 当前每页有多少条
      },

      // 列表
      dataList: null,
      roleInfo: {}, // 详细信息
      total: 0, // 总共有多少条数据
      editDialogVisible: false, // 修改对话框显示与隐藏
      addDialogVisible: false, // add对话框显示与隐藏
      editrules: { // 修改规则
        remarks: [
          { required: true, message: '请输入橘色说明！', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名！', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]

      }
    }
  },
  watch: {

    addDialogVisible(val) {
    // 检测添加对话框显示状态  清除数据
      if (val === false) {
        this.roleInfo.remarks = ''
        this.roleInfo.roleName = ''
        this.roleInfo.id = ''
        this.$refs.treeRef.setCheckedKeys([]) // 清除树已选中节点
      }
    },
    editDialogVisible(val) {
    // 检测修改对话框显示状态  清除数据
      if (val === false) {
        this.roleInfo.remarks = ''
        this.roleInfo.roleName = ''
        this.roleInfo.id = ''
        this.$refs.treeRef.setCheckedKeys([]) // 清除树已选中节点
      }
    }
  },
  created() {
    this.getPermissionList()
    this.getDataList()
  },

  methods: {
    async dell_feed_id(id) {
      // 执行删除
      const { data: res } = await this.$post('Roles/del', { id: id })
      console.log(res.data)
      if (res.code !== 200) {
        return this.$message.error('删除信息失败')
      }
      this.$message.success('删除成功')
      this.getDataList()
    },
    DelbyID(id) {
      // 删除发放记录
      console.log('kill' + id)
      this.$confirm('此操作将删除编号为 ' + id + '的角色记录, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dell_feed_id(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    setChecked(a, b) {
      // 处理树点击事件
      this.defaultCheckedKkeys = b.checkedKeys
    },

    getPermissionIds() {
      const CheckedKeys = this.$refs.treeRef.getCheckedKeys()
      console.log('CheckedKeys=', CheckedKeys)
      const permissionIds = []
      for (let i = 0; i < CheckedKeys.length; i++) {
        permissionIds.push(CheckedKeys[i])
      }

      // 数组转换为字符串
      const IDstr = permissionIds.join(',')
      console.log('IDstr=', IDstr)
      this.roleInfo.permissionIds = IDstr
    },
    async getPermissionList() {
      // 获取权限列表
      console.log(this.queryInfo)
      const { data: res } = await this.$post('Permissions/GetListAll')
      console.log(res)
      if (res.code !== 200) return this.$message.error('获取数据失败' + res.message)
      this.PermissiondataList = res.data
      console.log(this.PermissiondataList)
    },
    // 优化异步操作 async await
    async getDataList() {
      console.log(this.queryInfo)
      const { data: res } = await this.$post('Roles/GetList', this.queryInfo)
      console.log(res)
      if (res.code !== 200) return this.$message.error('获取数据失败' + res.message)
      this.dataList = res.data.records
      console.log(this.dataList)
      this.total = res.data.total
    },
    // 显示修改对话框 事件处理函数
    async showEditDialog(id) {
      console.log(id)
      // 获取角色信息和角色对应的权限信息

      const { data: res } = await this.$post('Roles/detail', { id: id })
      console.log(res.data)
      if (res.code !== 200) {
        return this.$message.error('读取信息失败' + res.message)
      }
      this.roleInfo = res.data.detail
      // 设置选中的发射台
      if (this.roleInfo.permissionIds !== undefined) {
        const dataStr = this.roleInfo.permissionIds// 原始字符串
        const dataStrArr = dataStr.split(',')// 分割成字符串数组
        const dataIntArr = []// 保存转换后的整型字符串
        dataStrArr.forEach(function(data, index, arr) {
          dataIntArr.push(+data)
        })
        this.defaultCheckedKkeys = dataIntArr// 设置默认选中节点
      }

      this.editDialogVisible = true
    },
    saveEdit() {
    // 修改确定
      this.$refs.editform.validate(async valid => {
        console.log(valid)
        if (!valid) {
          return false
        } // 验证失败
        // 发起添加用户表单的网络请求
        this.getPermissionIds()
        const { data: res } = await this.$post(
          'Roles/edit', this.roleInfo
        )
        if (res.code !== 200) {
          return this.$message.error('修改失败！' + res.message)
        }
        this.$message.success('修改成功！')

        this.editDialogVisible = false
        this.getDataList()
      })
    },
    saveAdd() {
    // 添加确定
      this.$refs.addform.validate(async valid => {
        console.log(valid)
        if (!valid) {
          return false
        } // 验证失败
        // 发起添加用户表单的网络请求
        this.getPermissionIds()
        const { data: res } = await this.$post(
          'Roles/add', this.roleInfo
        )
        if (res.code !== 200) {
          return this.$message.error('添加失败！' + res.message)
        }
        this.$message.success('添加成功！')
        this.addDialogVisible = false
        // this.getDataList()
      })
    },
    EditDialogClosed() { // edit关闭窗口
      this.editDialogVisible = false
    },
    addDialogClosed() { // add关闭窗口
      this.addDialogVisible = false
    },
    // 监听分页数量设置
    handleSizeChange(newsize) {
      console.log(newsize)
      console.log(this.queryInfo.pagesize)
      this.queryInfo.pagesize = newsize
      this.getDataList()
    },
    // 监听页码值改变
    handleCurrentChange(newpage) {
      console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getDataList()
    }

  }
}
</script>
<style lang="less" scoped>
  .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
</style>
